﻿using FileStorageCenter.Services.Models;
using System.Collections.Concurrent;

namespace FileStorageCenter.Services.Services.Impl;

internal sealed class UploadQueueProvider : IUploadQueueProvider<UploadModel>
{
    private readonly ConcurrentQueue<UploadModel> _uploadQueue = new();

    public bool IsEmpty => _uploadQueue.IsEmpty;

    public void Enqueue(UploadModel model)
    {
        model.Buffer.Position = 0;

        var newBuffer = new MemoryStream();

        model.Buffer.CopyTo(newBuffer);

        newBuffer.Position = 0;

        model.Buffer = newBuffer;

        _uploadQueue.Enqueue(model);
    }

    public void EnqueueRange(IEnumerable<UploadModel> models)
    {
        foreach (var model in models)
        {
            Enqueue(model);
        }
    }

    public bool TryDequeue(out UploadModel model)
    {
        model = new();

        if (_uploadQueue.TryDequeue(out var tmodel))
        {
            model = tmodel;

            return true;
        }

        return false;
    }
}